﻿using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlaceOrder_Core.Services
{
    /// <summary>
    /// 数据库连接池
    /// </summary>
    public class ConnectionPool
    {
        private readonly string _connectionString;
        private readonly Queue<IDbConnection> _pool = new Queue<IDbConnection>();
        private readonly object _lock = new object();

        public ConnectionPool(string connectionString, int maxPoolSize)
        {
            _connectionString = connectionString;
            for (int i = 0; i < maxPoolSize; i++)
            {
                var connection = CreateConnection();
                _pool.Enqueue(connection);
            }
        }

        public IDbConnection GetConnection()
        {
            lock (_lock)
            {
                if (_pool.Count > 0)
                {
                    return _pool.Dequeue();
                }
                else
                {
                    var connection = CreateConnection();
                    return connection;
                }
            }
        }

        public void ReleaseConnection(IDbConnection connection)
        {
            lock (_lock)
            {
                _pool.Enqueue(connection);
            }
        }

        private IDbConnection CreateConnection()
        {
            var connection = new NpgsqlConnection(_connectionString);
            connection.Open();
            return connection;
        }
    }

}
